package controllers

import (
	"books_db/models"
	beego "github.com/beego/beego/v2/server/web"
)

type BookController struct {
	beego.Controller
}

func (c *BookController) Create() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var book models.Book
	book.Author = c.GetString("author")
	book.Title = c.GetString("title")
	book.Type = c.GetString("type")
	book.Image = models.GetImageUrlByImageFile(c.GetFile("image"))
	book.AddressUrl = "http://127.0.0.1:8080/static/" + book.Title
	if book.Title == "" {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "未填标题",
		}
		c.ServeJSON()
		c.StopRun()
	}
	if book.Author == "" {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "未填作者",
		}
		c.ServeJSON()
		c.StopRun()
	}
	if book.Type == "" {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "未填分类",
		}
		c.ServeJSON()
		c.StopRun()
	}
	if book.CreateBook() != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		c.StopRun()
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "新建成功",
	}
	c.ServeJSON()
}
func (c *BookController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var FromFindBookList models.Book
	var title string
	title = c.GetString("title")
	BL, err := FromFindBookList.GetBooksList(title)
	if err != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		c.StopRun()
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "查询成功",
		"Data": BL,
	}
	c.ServeJSON()
}
func (c *BookController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var book models.Book
	id, _ := c.GetInt("id")
	book.ID = uint(id)
	if book.DelBook() != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		c.StopRun()
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "删除成功",
	}
	c.ServeJSON()
}
